import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores/userStore'

const request = axios.create({
  baseURL: 'https://keai.cool/api',
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => response,
  async error => {
    // 如果不是登录接口，且返回 401
    if (error.response?.status === 401 && !error.config.url.includes('/auth/login')) {
      const userStore = useUserStore()
      // 只有在非 /auth/profile 接口时才跳转登录页
      if (!error.config.url.includes('/auth/profile')) {
        userStore.logout()
        router.push('/login')
      }
    }
    return Promise.reject(error)
  }
)

// AI模型相关接口
export const getModels = () => request.get('/models')
export const getDefaultModel = () => request.get('/models/default')
export const createModel = (data: any) => request.post('/models', data)
export const updateModel = (id: number, data: any) => request.put(`/models/${id}`, data)
export const deleteModel = (id: number) => request.delete(`/models/${id}`)
export const setDefaultModel = (id: number) => request.post(`/models/${id}/default`)

// 提示词相关接口
export const getPrompts = () => request.get('/prompts')
export const createPrompt = (data: any) => request.post('/prompts', data)
export const updatePrompt = (id: number, data: any) => request.put(`/prompts/${id}`, data)
export const deletePrompt = (id: number) => request.delete(`/prompts/${id}`)
export const setDefaultPrompt = (id: number) => request.post(`/prompts/${id}/default`)

export default request 